<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=2">
<meta name="theme-color" content="#222">
<meta name="generator" content="Hexo 5.4.0">
  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png">
  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon-32x32-next.png">
  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon-16x16-next.png">
  <link rel="mask-icon" href="/images/logo.svg" color="#222">

<link rel="stylesheet" href="/css/main.css">


<link rel="stylesheet" href="/lib/font-awesome/css/all.min.css">

<script id="hexo-configurations">
    var NexT = window.NexT || {};
    var CONFIG = {"hostname":"blog.zeroable.cn","root":"/","scheme":"Pisces","version":"7.8.0","exturl":false,"sidebar":{"position":"left","display":"post","padding":18,"offset":12,"onmobile":false},"copycode":{"enable":false,"show_result":false,"style":null},"back2top":{"enable":true,"sidebar":false,"scrollpercent":false},"bookmark":{"enable":false,"color":"#222","save":"auto"},"fancybox":false,"mediumzoom":false,"lazyload":false,"pangu":false,"comments":{"style":"tabs","active":null,"storage":true,"lazyload":false,"nav":null},"algolia":{"hits":{"per_page":10},"labels":{"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}},"localsearch":{"enable":false,"trigger":"auto","top_n_per_article":1,"unescape":false,"preload":false},"motion":{"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}}};
  </script>

  <meta name="description" content="微信公众号：码农小谭，一个热爱coding、生活、分享、探讨的打工人，如果我的文章对你有帮助，麻烦给个关注吧~公众号分享技术博文、生活百事、欢迎关注~资料获取方式，无任何套路，也不需要解压验证码，如下：需要java相关资料请回复【java】需要数据库相关资料请回复【数据库】需要计算机网络相关资料请回复【计算机网络】需要操作系统相关资料请回复【操作系统】需要算法相关资料请回复【算法】如果资料链接失">
<meta property="og:type" content="article">
<meta property="og:title" content="netty源码解析01-netty服务端启动过程">
<meta property="og:url" content="https://blog.zeroable.cn/2021/10/08/netty%E6%BA%90%E7%A0%81%E8%A7%A3%E6%9E%9001-netty%E6%9C%8D%E5%8A%A1%E7%AB%AF%E5%90%AF%E5%8A%A8%E8%BF%87%E7%A8%8B/index.html">
<meta property="og:site_name" content="zeroable">
<meta property="og:description" content="微信公众号：码农小谭，一个热爱coding、生活、分享、探讨的打工人，如果我的文章对你有帮助，麻烦给个关注吧~公众号分享技术博文、生活百事、欢迎关注~资料获取方式，无任何套路，也不需要解压验证码，如下：需要java相关资料请回复【java】需要数据库相关资料请回复【数据库】需要计算机网络相关资料请回复【计算机网络】需要操作系统相关资料请回复【操作系统】需要算法相关资料请回复【算法】如果资料链接失">
<meta property="og:locale" content="zh_CN">
<meta property="og:image" content="https://gitee.com/zeroable/ima/raw/master/img/EWM_GZH_MNXT.png">
<meta property="og:image" content="https://gitee.com/zeroable/ima/raw/master/img/EWM_GZH_MNXT.png">
<meta property="article:published_time" content="2021-10-08T02:17:55.000Z">
<meta property="article:modified_time" content="2021-11-18T08:01:44.420Z">
<meta property="article:author" content="zeroable">
<meta property="article:tag" content="netty">
<meta property="article:tag" content="java">
<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="https://gitee.com/zeroable/ima/raw/master/img/EWM_GZH_MNXT.png">

<link rel="canonical" href="https://blog.zeroable.cn/2021/10/08/netty%E6%BA%90%E7%A0%81%E8%A7%A3%E6%9E%9001-netty%E6%9C%8D%E5%8A%A1%E7%AB%AF%E5%90%AF%E5%8A%A8%E8%BF%87%E7%A8%8B/">


<script id="page-configurations">
  // https://hexo.io/docs/variables.html
  CONFIG.page = {
    sidebar: "",
    isHome : false,
    isPost : true,
    lang   : 'zh-CN'
  };
</script>

  <title>netty源码解析01-netty服务端启动过程 | zeroable</title>
  






  <noscript>
  <style>
  .use-motion .brand,
  .use-motion .menu-item,
  .sidebar-inner,
  .use-motion .post-block,
  .use-motion .pagination,
  .use-motion .comments,
  .use-motion .post-header,
  .use-motion .post-body,
  .use-motion .collection-header { opacity: initial; }

  .use-motion .site-title,
  .use-motion .site-subtitle {
    opacity: initial;
    top: initial;
  }

  .use-motion .logo-line-before i { left: initial; }
  .use-motion .logo-line-after i { right: initial; }
  </style>
</noscript>

</head>

<body itemscope itemtype="http://schema.org/WebPage">
  <div class="container use-motion">
    <div class="headband"></div>

    <header class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-container">
  <div class="site-nav-toggle">
    <div class="toggle" aria-label="切换导航栏">
      <span class="toggle-line toggle-line-first"></span>
      <span class="toggle-line toggle-line-middle"></span>
      <span class="toggle-line toggle-line-last"></span>
    </div>
  </div>

  <div class="site-meta">

    <a href="/" class="brand" rel="start">
      <span class="logo-line-before"><i></i></span>
      <h1 class="site-title">zeroable</h1>
      <span class="logo-line-after"><i></i></span>
    </a>
      <p class="site-subtitle" itemprop="description">微信公众号：码农小谭</p>
  </div>

  <div class="site-nav-right">
    <div class="toggle popup-trigger">
    </div>
  </div>
</div>




<nav class="site-nav">
  <ul id="menu" class="main-menu menu">
        <li class="menu-item menu-item-home">

    <a href="/" rel="section"><i class="fa fa-home fa-fw"></i>首页</a>

  </li>
        <li class="menu-item menu-item-archives">

    <a href="/archives/" rel="section"><i class="fa fa-archive fa-fw"></i>归档</a>

  </li>
        <li class="menu-item menu-item-categories">

    <a href="/categories/" rel="section"><i class="fa fa-th fa-fw"></i>分类</a>

  </li>
        <li class="menu-item menu-item-tags">

    <a href="/tags/" rel="section"><i class="fa fa-tags fa-fw"></i>标签</a>

  </li>
        <li class="menu-item menu-item-about">

    <a href="/about/" rel="section"><i class="fa fa-user fa-fw"></i>关于</a>

  </li>
  </ul>
</nav>




</div>
    </header>

    
  <div class="back-to-top">
    <i class="fa fa-arrow-up"></i>
    <span>0%</span>
  </div>


    <main class="main">
      <div class="main-inner">
        <div class="content-wrap">
          

          <div class="content post posts-expand">
            

    
  
  
  <article itemscope itemtype="http://schema.org/Article" class="post-block" lang="zh-CN">
    <link itemprop="mainEntityOfPage" href="https://blog.zeroable.cn/2021/10/08/netty%E6%BA%90%E7%A0%81%E8%A7%A3%E6%9E%9001-netty%E6%9C%8D%E5%8A%A1%E7%AB%AF%E5%90%AF%E5%8A%A8%E8%BF%87%E7%A8%8B/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="image" content="/images/avatar.gif">
      <meta itemprop="name" content="zeroable">
      <meta itemprop="description" content="种一棵树最好的时间是十年前，其次是现在。">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="zeroable">
    </span>
      <header class="post-header">
        <h1 class="post-title" itemprop="name headline">
          netty源码解析01-netty服务端启动过程
        </h1>

        <div class="post-meta">
            <span class="post-meta-item">
              <span class="post-meta-item-icon">
                <i class="far fa-calendar"></i>
              </span>
              <span class="post-meta-item-text">发表于</span>

              <time title="创建时间：2021-10-08 10:17:55" itemprop="dateCreated datePublished" datetime="2021-10-08T10:17:55+08:00">2021-10-08</time>
            </span>
              <span class="post-meta-item">
                <span class="post-meta-item-icon">
                  <i class="far fa-calendar-check"></i>
                </span>
                <span class="post-meta-item-text">更新于</span>
                <time title="修改时间：2021-11-18 16:01:44" itemprop="dateModified" datetime="2021-11-18T16:01:44+08:00">2021-11-18</time>
              </span>
            <span class="post-meta-item">
              <span class="post-meta-item-icon">
                <i class="far fa-folder"></i>
              </span>
              <span class="post-meta-item-text">分类于</span>
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/categories/java/" itemprop="url" rel="index"><span itemprop="name">java</span></a>
                </span>
                  ，
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/categories/java/netty/" itemprop="url" rel="index"><span itemprop="name">netty</span></a>
                </span>
            </span>

          
            <span class="post-meta-item" title="阅读次数" id="busuanzi_container_page_pv" style="display: none;">
              <span class="post-meta-item-icon">
                <i class="fa fa-eye"></i>
              </span>
              <span class="post-meta-item-text">阅读次数：</span>
              <span id="busuanzi_value_page_pv"></span>
            </span>

        </div>
      </header>

    
    
    
    <div class="post-body" itemprop="articleBody">

      
        <blockquote>
<p>微信公众号：码农小谭，一个热爱coding、生活、分享、探讨的打工人，如果我的文章对你有帮助，麻烦给个关注吧~<br>公众号分享技术博文、生活百事、欢迎关注~<br>资料获取方式，无任何套路，也不需要解压验证码，如下：<br>需要java相关资料请回复【java】<br>需要数据库相关资料请回复【数据库】<br>需要计算机网络相关资料请回复【计算机网络】<br>需要操作系统相关资料请回复【操作系统】<br>需要算法相关资料请回复【算法】<br>如果资料链接失效，请点击联系作者添加微信，第一时间会进行更新。</p>
</blockquote>
<p><img src="https://gitee.com/zeroable/ima/raw/master/img/EWM_GZH_MNXT.png"></p>
<blockquote>
<p>提示:如果没有听过或者使用过java nio 和netty，不建议直接阅读此文章，建议先去了解java nio 和netty之后再阅读此文章。</p>
</blockquote>
<span id="more"></span>

<h1 id="netty-服务端启动"><a href="#netty-服务端启动" class="headerlink" title="netty 服务端启动"></a>netty 服务端启动</h1><p>我们知道，netty是对java nio 的进一步的封装和优化，所以，在netty中，肯定有几行代码，创建了java  nio，所以，我们在了解netty服务端启动之前，肯定需要知道一下俩个问题：</p>
<ol>
<li>java nio 的socket是在哪里进行初始化的呢？</li>
<li>在哪里进行accept连接？</li>
</ol>
<h2 id="创建服务端Channel"><a href="#创建服务端Channel" class="headerlink" title="创建服务端Channel"></a>创建服务端Channel</h2><p>那么我们带着这俩个问题，进行阅读源码。为了防止你阅读此文章时过于迷茫，我先将大致的过程先写出来：</p>
<ol>
<li>创建服务端Channel。<ol>
<li><code>bind()</code>用户代码入口。</li>
<li><code>initAndRegister()</code>初始化并注册</li>
<li><code>newChannel()</code> 创建java服务端Channel。</li>
</ol>
</li>
<li>初始化服务端Channel。</li>
<li>注册selector。</li>
<li>绑定端口。</li>
</ol>
<p>首先我们先写一个简单的netty Server demo，如下：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br></pre></td><td class="code"><pre><span class="line">NioEventLoopGroup bossGroup = <span class="keyword">new</span> NioEventLoopGroup();</span><br><span class="line">NioEventLoopGroup workGroup = <span class="keyword">new</span> NioEventLoopGroup();</span><br><span class="line"><span class="keyword">try</span> &#123;</span><br><span class="line">    ServerBootstrap serverBootstrap = <span class="keyword">new</span> ServerBootstrap();</span><br><span class="line">    serverBootstrap.group(bossGroup, workGroup)</span><br><span class="line">        .channel(NioServerSocketChannel.class)</span><br><span class="line">        .childOption(ChannelOption.TCP_NODELAY, <span class="keyword">true</span>)</span><br><span class="line">        .childAttr(AttributeKey.newInstance(<span class="string">&quot;childAttr&quot;</span>), <span class="string">&quot;childAttr&quot;</span>)</span><br><span class="line">        .handler(<span class="keyword">new</span> ServerHandler())</span><br><span class="line">        .childHandler(<span class="keyword">new</span> ChannelInitializer() &#123;</span><br><span class="line">            <span class="meta">@Override</span></span><br><span class="line">            <span class="function"><span class="keyword">protected</span> <span class="keyword">void</span> <span class="title">initChannel</span><span class="params">(Channel ch)</span> <span class="keyword">throws</span> Exception </span>&#123;</span><br><span class="line">                <span class="comment">//ch.pipeline().addLast();</span></span><br><span class="line">            &#125;</span><br><span class="line">        &#125;);</span><br><span class="line">    ChannelFuture f = serverBootstrap.bind(<span class="number">9999</span>).sync();</span><br><span class="line">    f.channel().closeFuture().sync();</span><br><span class="line">&#125; <span class="keyword">catch</span> (InterruptedException e) &#123;</span><br><span class="line">    e.printStackTrace();</span><br><span class="line">&#125; <span class="keyword">finally</span> &#123;</span><br><span class="line">    bossGroup.shutdownGracefully();</span><br><span class="line">    workGroup.shutdownGracefully();</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h3 id="用户代码入口"><a href="#用户代码入口" class="headerlink" title="用户代码入口"></a>用户代码入口</h3><p>我们首先从第16行代码的<code>bind()</code> 方法进行查看源码。跟进去发现，最后是调用了<code>doBind(localAddress)</code>方法，如下：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> ChannelFuture <span class="title">bind</span><span class="params">(SocketAddress localAddress)</span> </span>&#123;</span><br><span class="line">    validate();</span><br><span class="line">    <span class="keyword">if</span> (localAddress == <span class="keyword">null</span>) &#123;</span><br><span class="line">    	<span class="keyword">throw</span> <span class="keyword">new</span> NullPointerException(<span class="string">&quot;localAddress&quot;</span>);</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="comment">//实际上是这个方法在做事情。</span></span><br><span class="line">    <span class="keyword">return</span> doBind(localAddress);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>继续去查看<code>doBind(localAddress)</code> 方法，发现他的实现如下：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">private</span> ChannelFuture <span class="title">doBind</span><span class="params">(<span class="keyword">final</span> SocketAddress localAddress)</span> </span>&#123;</span><br><span class="line">	<span class="comment">//1. 初始化并且注册，这一步就是创建一个java nio channel,</span></span><br><span class="line">	<span class="comment">//并且将之绑定到ChannelFuture，它是对Channel 的进一步封装。</span></span><br><span class="line">    <span class="keyword">final</span> ChannelFuture regFuture = initAndRegister();</span><br><span class="line">    <span class="keyword">final</span> Channel channel = regFuture.channel();</span><br><span class="line">    <span class="keyword">if</span> (regFuture.cause() != <span class="keyword">null</span>) &#123;</span><br><span class="line">    	<span class="keyword">return</span> regFuture;</span><br><span class="line">    &#125;</span><br><span class="line">	</span><br><span class="line">	<span class="comment">//下面的暂时不用管暂时就删掉了，不然看的好麻烦</span></span><br><span class="line">    <span class="comment">//dosomething...</span></span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h3 id="初始化并注册"><a href="#初始化并注册" class="headerlink" title="初始化并注册"></a>初始化并注册</h3><p>我们跟进<code>initAndRegister()</code>方法中，发现内容如下：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">final</span> ChannelFuture <span class="title">initAndRegister</span><span class="params">()</span> </span>&#123;</span><br><span class="line">    Channel channel = <span class="keyword">null</span>;</span><br><span class="line">    <span class="keyword">try</span> &#123;</span><br><span class="line">        <span class="comment">// 这里非常重要</span></span><br><span class="line">        channel = channelFactory.newChannel();</span><br><span class="line">        <span class="comment">//这里就是初始化channel，这里后面再讲。</span></span><br><span class="line">        init(channel);</span><br><span class="line">    &#125; <span class="keyword">catch</span> (Throwable t) &#123;</span><br><span class="line">        <span class="keyword">if</span> (channel != <span class="keyword">null</span>) &#123;</span><br><span class="line">            <span class="comment">// channel can be null if newChannel crashed (eg SocketException(&quot;too many open files&quot;))</span></span><br><span class="line">            channel.unsafe().closeForcibly();</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="comment">// as the Channel is not registered yet we need to force the usage of the GlobalEventExecutor</span></span><br><span class="line">        <span class="keyword">return</span> <span class="keyword">new</span> DefaultChannelPromise(channel, GlobalEventExecutor.INSTANCE).setFailure(t);</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="comment">//dosomething...</span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h3 id="创建java服务端Channel"><a href="#创建java服务端Channel" class="headerlink" title="创建java服务端Channel"></a>创建java服务端Channel</h3><p>我们继续通过第5行代码<code>channelFactory.newChannel();</code> 继续跟进去，发现她其实就是通过反射进行创建了一个对象：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@Override</span></span><br><span class="line"><span class="function"><span class="keyword">public</span> T <span class="title">newChannel</span><span class="params">()</span> </span>&#123;</span><br><span class="line">    <span class="keyword">try</span> &#123;</span><br><span class="line">    	<span class="keyword">return</span> clazz.newInstance();</span><br><span class="line">    &#125; <span class="keyword">catch</span> (Throwable t) &#123;</span><br><span class="line">    	<span class="keyword">throw</span> <span class="keyword">new</span> ChannelException(<span class="string">&quot;Unable to create Channel from class &quot;</span> + clazz, t);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>那么我们需要知道这个<code>clazz</code> 变量是哪个class对象，那就需要知道channelFactory是在哪里进行初始化的，我们直接回到demo代码中第6行：<code>channel(NioServerSocketChannel.class)</code> 跟踪这个方法发现：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br></pre></td><td class="code"><pre><span class="line">  <span class="function"><span class="keyword">public</span> B <span class="title">channel</span><span class="params">(Class&lt;? extends C&gt; channelClass)</span> </span>&#123;</span><br><span class="line">      <span class="keyword">if</span> (channelClass == <span class="keyword">null</span>) &#123;</span><br><span class="line">          <span class="keyword">throw</span> <span class="keyword">new</span> NullPointerException(<span class="string">&quot;channelClass&quot;</span>);</span><br><span class="line">      &#125;</span><br><span class="line">      <span class="comment">// 使用的是ReflectiveChannelFactory 类,clazz也就是我们demo 中传入的 NioServerSocketChannel.class 对象，中间还省略了一个重载方法，忽略。</span></span><br><span class="line">      <span class="keyword">return</span> channelFactory(<span class="keyword">new</span> ReflectiveChannelFactory&lt;C&gt;(channelClass));</span><br><span class="line">  &#125;</span><br><span class="line"></span><br><span class="line">  <span class="comment">/**</span></span><br><span class="line"><span class="comment">   * <span class="doctag">@deprecated</span> Use &#123;<span class="doctag">@link</span> #channelFactory(io.netty.channel.ChannelFactory)&#125; instead.</span></span><br><span class="line"><span class="comment">   */</span></span><br><span class="line">  <span class="meta">@Deprecated</span></span><br><span class="line">  <span class="meta">@SuppressWarnings(&quot;unchecked&quot;)</span></span><br><span class="line">  <span class="function"><span class="keyword">public</span> B <span class="title">channelFactory</span><span class="params">(ChannelFactory&lt;? extends C&gt; channelFactory)</span> </span>&#123;</span><br><span class="line">      <span class="keyword">if</span> (channelFactory == <span class="keyword">null</span>) &#123;</span><br><span class="line">          <span class="keyword">throw</span> <span class="keyword">new</span> NullPointerException(<span class="string">&quot;channelFactory&quot;</span>);</span><br><span class="line">      &#125;</span><br><span class="line">      <span class="keyword">if</span> (<span class="keyword">this</span>.channelFactory != <span class="keyword">null</span>) &#123;</span><br><span class="line">          <span class="keyword">throw</span> <span class="keyword">new</span> IllegalStateException(<span class="string">&quot;channelFactory set already&quot;</span>);</span><br><span class="line">      &#125;</span><br><span class="line"><span class="comment">//这里就对channelFactory 变量进行赋值。</span></span><br><span class="line">      <span class="keyword">this</span>.channelFactory = channelFactory;</span><br><span class="line">      <span class="keyword">return</span> (B) <span class="keyword">this</span>;</span><br><span class="line">  &#125;</span><br></pre></td></tr></table></figure>

<p>那么我们只需要关注NioServerSocketChannel类的构造函数做了哪些事情。我还是提前告诉你构造函数做了什么事情：</p>
<ol>
<li><code>newSocket()</code> 通过jdk来创建底层jdk channel。之前的俩个问题中的第一个问题就在这里进行了解决。</li>
<li><code>NIOServerSocketChannelConfig()</code> tcp参数配置类，比如backlog、recv buffer、send buffer等跟tcp参数相关的配置。</li>
<li><code>AbstractNioChannel()</code> 父类构造函数，调用 <code>ch.configureBlocking(false);</code> 设置阻塞模式为非阻塞。</li>
<li><code>AbstractChannel</code> 父类构造函数。创建此channel的id、unsafe、pipeline。</li>
</ol>
<h4 id="创建底层jdk-channel"><a href="#创建底层jdk-channel" class="headerlink" title="创建底层jdk channel"></a>创建底层jdk channel</h4><p>我们一步步来通过源码来看看这5步具体怎么实现的。首先我们看看<code>newSocket()</code> 做了什么事情，首先把NioServerSocketChannel的构造方法内容贴出来：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br></pre></td><td class="code"><pre><span class="line">   <span class="keyword">private</span> <span class="keyword">static</span> <span class="keyword">final</span> SelectorProvider DEFAULT_SELECTOR_PROVIDER = SelectorProvider.provider();</span><br><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment">    * Create a new instance</span></span><br><span class="line"><span class="comment">    */</span></span><br><span class="line">   <span class="function"><span class="keyword">public</span> <span class="title">NioServerSocketChannel</span><span class="params">()</span> </span>&#123;</span><br><span class="line">       <span class="comment">//这里是第一步,newSocket通过SelectorProvider创建了jdk底层的ServerSocketChannel，</span></span><br><span class="line">       <span class="comment">//而这个provider就是SelectorProvider.provider();</span></span><br><span class="line">       <span class="keyword">this</span>(newSocket(DEFAULT_SELECTOR_PROVIDER));</span><br><span class="line">   &#125;</span><br><span class="line"></span><br><span class="line">   <span class="function"><span class="keyword">private</span> <span class="keyword">static</span> ServerSocketChannel <span class="title">newSocket</span><span class="params">(SelectorProvider provider)</span> </span>&#123;</span><br><span class="line">       <span class="keyword">try</span> &#123;</span><br><span class="line">           <span class="comment">/**</span></span><br><span class="line"><span class="comment">            *  Use the &#123;<span class="doctag">@link</span> SelectorProvider&#125; to open &#123;<span class="doctag">@link</span> SocketChannel&#125; and so remove condition in</span></span><br><span class="line"><span class="comment">            *  &#123;<span class="doctag">@link</span> SelectorProvider#provider()&#125; which is called by each ServerSocketChannel.open() otherwise.</span></span><br><span class="line"><span class="comment">            *</span></span><br><span class="line"><span class="comment">            *  See &lt;a href=&quot;https://github.com/netty/netty/issues/2308&quot;&gt;#2308&lt;/a&gt;.</span></span><br><span class="line"><span class="comment">            */</span></span><br><span class="line">           <span class="keyword">return</span> provider.openServerSocketChannel();</span><br><span class="line">       &#125; <span class="keyword">catch</span> (IOException e) &#123;</span><br><span class="line">           <span class="keyword">throw</span> <span class="keyword">new</span> ChannelException(</span><br><span class="line">                   <span class="string">&quot;Failed to open a server socket.&quot;</span>, e);</span><br><span class="line">       &#125;</span><br><span class="line">   &#125;</span><br><span class="line"></span><br><span class="line">   <span class="comment">/**</span></span><br><span class="line"><span class="comment">    * Create a new instance using the given &#123;<span class="doctag">@link</span> ServerSocketChannel&#125;.</span></span><br><span class="line"><span class="comment">    */</span></span><br><span class="line">   <span class="function"><span class="keyword">public</span> <span class="title">NioServerSocketChannel</span><span class="params">(ServerSocketChannel channel)</span> </span>&#123;</span><br><span class="line">       <span class="keyword">super</span>(<span class="keyword">null</span>, channel, SelectionKey.OP_ACCEPT);</span><br><span class="line">       <span class="comment">//这里进行了第二步，创建了一个配置类。这个config的主要目的在后续对这个channel做一些tcp参数的获取，在set操作的时候，就通过这个config 去配置</span></span><br><span class="line">       config = <span class="keyword">new</span> NioServerSocketChannelConfig(<span class="keyword">this</span>, javaChannel().socket());</span><br><span class="line">   &#125;</span><br></pre></td></tr></table></figure>

<p>我们再通过上面代码的第30行，调用父类构造方法，一直跟进到<code>AbstractNioChannel</code>类的构造方法：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">protected</span> <span class="title">AbstractNioChannel</span><span class="params">(Channel parent, SelectableChannel ch, <span class="keyword">int</span> readInterestOp)</span> </span>&#123;</span><br><span class="line">    <span class="comment">//这里是第三步，这里是父类的构造方法，生成channel的id、unsafe、pipeline 属性。</span></span><br><span class="line">    <span class="keyword">super</span>(parent);</span><br><span class="line">    <span class="keyword">this</span>.ch = ch;</span><br><span class="line">    <span class="keyword">this</span>.readInterestOp = readInterestOp;</span><br><span class="line">    <span class="keyword">try</span> &#123;</span><br><span class="line">        <span class="comment">//这里是第四步，这里设置channel 的阻塞模式为非阻塞模式。</span></span><br><span class="line">        ch.configureBlocking(<span class="keyword">false</span>);</span><br><span class="line">    &#125; <span class="keyword">catch</span> (IOException e) &#123;</span><br><span class="line">        <span class="keyword">try</span> &#123;</span><br><span class="line">            ch.close();</span><br><span class="line">        &#125; <span class="keyword">catch</span> (IOException e2) &#123;</span><br><span class="line">            <span class="keyword">if</span> (logger.isWarnEnabled()) &#123;</span><br><span class="line">                logger.warn(</span><br><span class="line">                        <span class="string">&quot;Failed to close a partially initialized socket.&quot;</span>, e2);</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">throw</span> <span class="keyword">new</span> ChannelException(<span class="string">&quot;Failed to enter non-blocking mode.&quot;</span>, e);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>最后一步，生成channel 的id 、 unsafe、pipline。</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">protected</span> <span class="title">AbstractChannel</span><span class="params">(Channel parent)</span> </span>&#123;</span><br><span class="line">    <span class="keyword">this</span>.parent = parent;</span><br><span class="line">    id = newId();</span><br><span class="line">    unsafe = newUnsafe();</span><br><span class="line">    pipeline = newChannelPipeline();</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h2 id="初始化Channel"><a href="#初始化Channel" class="headerlink" title="初始化Channel"></a>初始化Channel</h2><p>还记得之前的那个<code>initAndRegister()</code>方法中的<code>init()</code> 吗？不记得可以去看看在哪里哦，那<code>init()</code> 做了哪些事情呢？我还是提前告诉你，好让你的提前知道，没有那么迷茫。</p>
<ol>
<li>设置ChannelOptions 、ChannelAttrs。</li>
<li>设置childOptions、childAttrs。每次accept一个新连接，就会用户自定义的这俩个属性配置上去。</li>
<li><code>config handler</code> 配置服务端pipline。这个的逻辑链也会是在用户代码里面的handler方法进行设置。</li>
<li><code>add ServerBootstrapAcceptor </code> 添加连接器。服务端的pipline都会有一个ServerBootstrapAcceptor这个特殊的处理器。这个处理器主要用于给accept一个新连接分配一个nio的线程。</li>
</ol>
<p>我们开始从<code>init(channel)</code> 入手，发现这个是一个abstract 方法，有俩个子类，我们分析的服务端，我们选择ServerBootstrap类，内容如下：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br></pre></td><td class="code"><pre><span class="line">  <span class="meta">@Override</span></span><br><span class="line">  <span class="function"><span class="keyword">void</span> <span class="title">init</span><span class="params">(Channel channel)</span> <span class="keyword">throws</span> Exception </span>&#123;</span><br><span class="line">      <span class="comment">//第一步，设置ChannelOptions、ChannelAttrs。首先获取options</span></span><br><span class="line">      <span class="keyword">final</span> Map&lt;ChannelOption&lt;?&gt;, Object&gt; options = options0();</span><br><span class="line">      <span class="keyword">synchronized</span> (options) &#123;</span><br><span class="line">          <span class="comment">//设置Options,这里的config就是我们前面说过的NioServerSocketChannelConfig</span></span><br><span class="line">          channel.config().setOptions(options);</span><br><span class="line">      &#125;</span><br><span class="line"><span class="comment">//这里进行ChannelAttrs属性的设置。用于绑定用户自定义的一些channel属性。</span></span><br><span class="line">      <span class="keyword">final</span> Map&lt;AttributeKey&lt;?&gt;, Object&gt; attrs = attrs0();</span><br><span class="line">      <span class="keyword">synchronized</span> (attrs) &#123;</span><br><span class="line">          <span class="comment">//循环绑定到channel的attrs中。</span></span><br><span class="line">          <span class="keyword">for</span> (Entry&lt;AttributeKey&lt;?&gt;, Object&gt; e: attrs.entrySet()) &#123;</span><br><span class="line">              <span class="meta">@SuppressWarnings(&quot;unchecked&quot;)</span></span><br><span class="line">              AttributeKey&lt;Object&gt; key = (AttributeKey&lt;Object&gt;) e.getKey();</span><br><span class="line">              channel.attr(key).set(e.getValue());</span><br><span class="line">          &#125;</span><br><span class="line">      &#125;</span><br><span class="line"></span><br><span class="line">      ChannelPipeline p = channel.pipeline();</span><br><span class="line"><span class="comment">//下面会用到，这就是用户自定义的childGroup</span></span><br><span class="line">      <span class="keyword">final</span> EventLoopGroup currentChildGroup = childGroup;</span><br><span class="line">      <span class="comment">//下面会用到，这就是用户自定义的childHandler</span></span><br><span class="line">      <span class="keyword">final</span> ChannelHandler currentChildHandler = childHandler;</span><br><span class="line">      <span class="keyword">final</span> Entry&lt;ChannelOption&lt;?&gt;, Object&gt;[] currentChildOptions;</span><br><span class="line">      <span class="keyword">final</span> Entry&lt;AttributeKey&lt;?&gt;, Object&gt;[] currentChildAttrs;</span><br><span class="line">      <span class="comment">//这里是保存了childOptions 和childAttrs。和上面保存ChannelOptions、ChannelAttrs差不多，这是比较简单的。</span></span><br><span class="line">      <span class="keyword">synchronized</span> (childOptions) &#123;</span><br><span class="line">          currentChildOptions = childOptions.entrySet().toArray(newOptionArray(childOptions.size()));</span><br><span class="line">      &#125;</span><br><span class="line">      <span class="keyword">synchronized</span> (childAttrs) &#123;</span><br><span class="line">          currentChildAttrs = childAttrs.entrySet().toArray(newAttrArray(childAttrs.size()));</span><br><span class="line">      &#125;</span><br><span class="line"><span class="comment">//配置服务端pipline。</span></span><br><span class="line">      p.addLast(<span class="keyword">new</span> ChannelInitializer&lt;Channel&gt;() &#123;</span><br><span class="line">          <span class="meta">@Override</span></span><br><span class="line">          <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">initChannel</span><span class="params">(Channel ch)</span> <span class="keyword">throws</span> Exception </span>&#123;</span><br><span class="line">              <span class="comment">//这里拿到pipline ，然后将用户添加的handler添加到pipline链上。</span></span><br><span class="line">              <span class="keyword">final</span> ChannelPipeline pipeline = ch.pipeline();</span><br><span class="line">              <span class="comment">//这里我们分析一下config.handler(); 的handler是在哪里设置的。</span></span><br><span class="line">              ChannelHandler handler = config.handler();</span><br><span class="line">              <span class="keyword">if</span> (handler != <span class="keyword">null</span>) &#123;</span><br><span class="line">                  pipeline.addLast(handler);</span><br><span class="line">              &#125;</span><br><span class="line"></span><br><span class="line">              <span class="comment">// We add this handler via the EventLoop as the user may have used a ChannelInitializer as handler.</span></span><br><span class="line">              <span class="comment">// In this case the initChannel(...) method will only be called after this method returns. Because</span></span><br><span class="line">              <span class="comment">// of this we need to ensure we add our handler in a delayed fashion so all the users handler are</span></span><br><span class="line">              <span class="comment">// placed in front of the ServerBootstrapAcceptor.</span></span><br><span class="line">              ch.eventLoop().execute(<span class="keyword">new</span> Runnable() &#123;</span><br><span class="line">                  <span class="meta">@Override</span></span><br><span class="line">                  <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">run</span><span class="params">()</span> </span>&#123;</span><br><span class="line">                      <span class="comment">//将用户自定义的childGroup、childHandler、ChildOptions、ChildAttrs放入这个特殊的handler中，这个特殊的handler主要是用于处理新连接的。</span></span><br><span class="line">                      pipeline.addLast(<span class="keyword">new</span> ServerBootstrapAcceptor(</span><br><span class="line">                              currentChildGroup, currentChildHandler, currentChildOptions, currentChildAttrs));</span><br><span class="line">                  &#125;</span><br><span class="line">              &#125;);</span><br><span class="line">          &#125;</span><br><span class="line">      &#125;);</span><br><span class="line">  &#125;</span><br></pre></td></tr></table></figure>

<p>我们在分析之前，我们先来看看这个demo中的第9行代码<code>.handler(new ServerHandler())</code> 看看handler方法中做了什么事情。其实非常简单，就是对变量的赋值，保存我们用户的自定义handler。代码就不贴出来了，自己点进去看下吧。然后我们回到<code>init</code>方法，其实也就是拿到保存的handler变量。拿到之后就将用户自定义的handler 添加到pipline中。</p>
<p>那么到了我们最后一个过程，添加一个<code>ServerBootstrapAcceptor</code> 其实他是一个特殊的handler。这里就不详细去介绍这个handler了，后面会进行详细讲解。</p>
<h2 id="注册Selector"><a href="#注册Selector" class="headerlink" title="注册Selector"></a>注册Selector</h2><p>当创建和初始化完成之后，接下来就是将这个channel注册到事件轮询器Selector上去。让我们一起来看看他的一个注册的过程吧。首先我们从<code>initAndRegister()</code> 开始查看，发现他有如下一段代码：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">final</span> ChannelFuture <span class="title">initAndRegister</span><span class="params">()</span> </span>&#123;</span><br><span class="line">    Channel channel = <span class="keyword">null</span>;</span><br><span class="line">    <span class="keyword">try</span> &#123;</span><br><span class="line">        channel = channelFactory.newChannel();</span><br><span class="line">        init(channel);</span><br><span class="line">    &#125; <span class="keyword">catch</span> (Throwable t) &#123;</span><br><span class="line">        <span class="keyword">if</span> (channel != <span class="keyword">null</span>) &#123;</span><br><span class="line">            <span class="comment">// channel can be null if newChannel crashed (eg SocketException(&quot;too many open files&quot;))</span></span><br><span class="line">            channel.unsafe().closeForcibly();</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="comment">// as the Channel is not registered yet we need to force the usage of the GlobalEventExecutor</span></span><br><span class="line">        <span class="keyword">return</span> <span class="keyword">new</span> DefaultChannelPromise(channel, GlobalEventExecutor.INSTANCE).setFailure(t);</span><br><span class="line">    &#125;</span><br><span class="line">	<span class="comment">// 注册到Selector就在这个方法中。</span></span><br><span class="line">    ChannelFuture regFuture = config().group().register(channel);</span><br><span class="line">    <span class="keyword">if</span> (regFuture.cause() != <span class="keyword">null</span>) &#123;</span><br><span class="line">        <span class="keyword">if</span> (channel.isRegistered()) &#123;</span><br><span class="line">            channel.close();</span><br><span class="line">        &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">            channel.unsafe().closeForcibly();</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">// If we are here and the promise is not failed, it&#x27;s one of the following cases:</span></span><br><span class="line">    <span class="comment">// 1) If we attempted registration from the event loop, the registration has been completed at this point.</span></span><br><span class="line">    <span class="comment">//    i.e. It&#x27;s safe to attempt bind() or connect() now because the channel has been registered.</span></span><br><span class="line">    <span class="comment">// 2) If we attempted registration from the other thread, the registration request has been successfully</span></span><br><span class="line">    <span class="comment">//    added to the event loop&#x27;s task queue for later execution.</span></span><br><span class="line">    <span class="comment">//    i.e. It&#x27;s safe to attempt bind() or connect() now:</span></span><br><span class="line">    <span class="comment">//         because bind() or connect() will be executed *after* the scheduled registration task is executed</span></span><br><span class="line">    <span class="comment">//         because register(), bind(), and connect() are all bound to the same thread.</span></span><br><span class="line"></span><br><span class="line">    <span class="keyword">return</span> regFuture;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>上面代码的：<code>ChannelFuture regFuture = config().group().register(channel);</code> 这里就进行了注册。让我们查看这个注册Selector过程，netty一共做了多少事情吧，大致的流程如下：</p>
<ol>
<li>最终是调用了<code>AbstractChannel.register(channel);</code>方法，这是入口。(<strong>这里比较绕，需要知道EventLoopGroup和EventLoop之间的关系和创建流程，这个并不是这篇文章的重点，所以暂时忽略掉，先告诉你结论。大概的流程就是：这里<code>AbstractChannel</code>的最终子类就是一个EventLoop也就是在EventLoopGroup创建的时候根据传入的线程数创建对应的EventLoop实例，通过一个数组进行保存，然后通过一个chooser根据下标进行选择对用的EventLoop进行执行，后面文章会详细讲解EventLoopGroup和EventLoop，先不需要知道详细的过程。</strong>)</li>
<li>调用<code>this.eventLoop = eventLoop</code>; 用来绑定NIO线程，也就是eventLoop。</li>
<li>调用<code>register0();</code>这个是实际的注册。<ol>
<li>调用<code>doRegister();</code>进行jdk底层注册。</li>
<li>调用<code>invokeHandlerAddedIfNeeded();</code>做一些事件的回调，比如我们开发者在添加一些handler到netty的channel上时，在这个过程，就会触发到我们的用户的回调。</li>
<li>调用<code>fireChannelRegistered()</code> 进行事件传播。将channel注册成功的事件传播到用户的代码中。</li>
</ol>
</li>
</ol>
<p>那我们现在回到<code>AbstractChannel</code>中的<code>register</code> 方法中。代码如下：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//AbstractChannel.java</span></span><br><span class="line"><span class="meta">@Override</span></span><br><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">final</span> <span class="keyword">void</span> <span class="title">register</span><span class="params">(EventLoop eventLoop, <span class="keyword">final</span> ChannelPromise promise)</span> </span>&#123;    </span><br><span class="line">    <span class="keyword">if</span> (isRegistered()) &#123;</span><br><span class="line">        promise.setFailure(<span class="keyword">new</span> IllegalStateException(<span class="string">&quot;registered to an event loop already&quot;</span>));</span><br><span class="line">        <span class="keyword">return</span>;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">if</span> (!isCompatible(eventLoop)) &#123;</span><br><span class="line">        promise.setFailure(</span><br><span class="line">            <span class="keyword">new</span> IllegalStateException(<span class="string">&quot;incompatible event loop type: &quot;</span> + eventLoop.getClass().getName()));</span><br><span class="line">        <span class="keyword">return</span>;</span><br><span class="line">    &#125;</span><br><span class="line">	<span class="comment">//这里就进行eventLoop的绑定。</span></span><br><span class="line">    AbstractChannel.<span class="keyword">this</span>.eventLoop = eventLoop;</span><br><span class="line"></span><br><span class="line">    <span class="comment">//执行register0();</span></span><br><span class="line">    <span class="comment">//这里是判断执行当前方法的线程是否为当前的这个eventLoop中的线程，如果是，那么就直接执行，否则就使用eventLoop中的线程去执行</span></span><br><span class="line">    <span class="keyword">if</span> (eventLoop.inEventLoop()) &#123;</span><br><span class="line">        register0(promise);</span><br><span class="line">    &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">        <span class="keyword">try</span> &#123;</span><br><span class="line">            eventLoop.execute(<span class="keyword">new</span> Runnable() &#123;</span><br><span class="line">                <span class="meta">@Override</span></span><br><span class="line">                <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">run</span><span class="params">()</span> </span>&#123;</span><br><span class="line">                    register0(promise);</span><br><span class="line">                &#125;</span><br><span class="line">            &#125;);</span><br><span class="line">        &#125; <span class="keyword">catch</span> (Throwable t) &#123;</span><br><span class="line">            logger.warn(</span><br><span class="line">                <span class="string">&quot;Force-closing a channel whose registration task was not accepted by an event loop: &#123;&#125;&quot;</span>,</span><br><span class="line">                AbstractChannel.<span class="keyword">this</span>, t);</span><br><span class="line">            closeForcibly();</span><br><span class="line">            closeFuture.setClosed();</span><br><span class="line">            safeSetFailure(promise, t);</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>正如代码中的注释，最后是通过调用<code>register0();</code>方法进行注册。但是我们可以看到，注册前netty对当前线程进行了判断，判断当前线程是不是一个eventLoop线程，我们查看<code>eventLoop.inEventLoop()</code> 方法发现，就是将当前线程实体作为参数传给一个重写方法，即：<code>inEventLoop(Thread.currentThread());</code> 然后再进去发现，只有一行代码，就是<code>return thread == this.thread;</code> 其中<code>this.thread</code> 就是eventLoop中的线程。了解了这个之后，我们再来查看<code>register0();</code> 到底干了些啥？流程如下：</p>
<ol>
<li>调用<code>doRegister();</code>进行真正的调用。</li>
<li>调用<code>pipeline.invokeHandlerAddedIfNeeded();</code> 进行通知，也就是会去执行我们用户代码中handler实例的<code>handlerAdded(ChannelHandlerContext ctx);</code>方法。</li>
<li>调用<code>pipeline.fireChannelRegistered();</code>进行通知，也就是会去执行我们用户代码里面的handler实例的<code>channelRegistered(ChannelHandlerContext ctx);</code>方法。</li>
</ol>
<p>pipeline后续文章会继续讲解，这里忽略，只需要知道这里进行了通知就行，然后我们查看<code>doRegister();</code>方法，这个方法具体实现在<code>AbstractNioChannel</code>类中，代码如下：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@Override</span></span><br><span class="line"><span class="function"><span class="keyword">protected</span> <span class="keyword">void</span> <span class="title">doRegister</span><span class="params">()</span> <span class="keyword">throws</span> Exception </span>&#123;</span><br><span class="line">    <span class="keyword">boolean</span> selected = <span class="keyword">false</span>;</span><br><span class="line">    <span class="keyword">for</span> (;;) &#123;</span><br><span class="line">        <span class="keyword">try</span> &#123;</span><br><span class="line">            selectionKey = javaChannel().register(eventLoop().selector, <span class="number">0</span>, <span class="keyword">this</span>);</span><br><span class="line">            <span class="keyword">return</span>;</span><br><span class="line">        &#125; <span class="keyword">catch</span> (CancelledKeyException e) &#123;</span><br><span class="line">            <span class="keyword">if</span> (!selected) &#123;</span><br><span class="line">                <span class="comment">// Force the Selector to select now as the &quot;canceled&quot; SelectionKey may still be</span></span><br><span class="line">                <span class="comment">// cached and not removed because no Select.select(..) operation was called yet.</span></span><br><span class="line">                eventLoop().selectNow();</span><br><span class="line">                selected = <span class="keyword">true</span>;</span><br><span class="line">            &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">                <span class="comment">// We forced a select operation on the selector before but the SelectionKey is still cached</span></span><br><span class="line">                <span class="comment">// for whatever reason. JDK bug ?</span></span><br><span class="line">                <span class="keyword">throw</span> e;</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>其实就是在这里，进行了jdk底层的nio的注册，并且将当前的这个channel作为一个<code>attachment</code>绑定到jdk底层的channel中，方便后续获取。到这里，就已经注册好jdk的nio的channel，并且将netty的channel注册到jdk nio 的channel上。</p>
<h2 id="绑定端口"><a href="#绑定端口" class="headerlink" title="绑定端口"></a>绑定端口</h2><p>接下来就是进行端口的绑定，回到我们调用<code>initAndRegister()</code>的地方，也就是<code>AbstractBootStrap.doBind();</code>方法。不难发现，最终是调用<code>doBind0();</code>进行最终的绑定。而<code>doBind0();</code>也是调用<code>channel.bind(localAddress, promise).addListener(ChannelFutureListener.CLOSE_ON_FAILURE);</code>。然后层层跟进，发现他是通过pipeline进行绑定，最终还是到达<code>AbstractChannel.AbstractUnsafe</code>类的<code>bind();</code>，这里做了俩件事情：</p>
<ol>
<li>先获取<code>isActive();</code></li>
<li>调用<code>doBind();</code>方法。</li>
<li>当只有执行<code>doBind();</code>方法前isActive是false,执行之后是true,才会去进行通知，触发用户代码中handler的<code>channelActive(ctx);</code>。</li>
</ol>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@Override</span></span><br><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">final</span> <span class="keyword">void</span> <span class="title">bind</span><span class="params">(<span class="keyword">final</span> SocketAddress localAddress, <span class="keyword">final</span> ChannelPromise promise)</span> </span>&#123;</span><br><span class="line">    assertEventLoop();</span><br><span class="line"></span><br><span class="line">    <span class="keyword">if</span> (!promise.setUncancellable() || !ensureOpen(promise)) &#123;</span><br><span class="line">        <span class="keyword">return</span>;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">// See: https://github.com/netty/netty/issues/576</span></span><br><span class="line">    <span class="keyword">if</span> (Boolean.TRUE.equals(config().getOption(ChannelOption.SO_BROADCAST)) &amp;&amp;</span><br><span class="line">        localAddress <span class="keyword">instanceof</span> InetSocketAddress &amp;&amp;</span><br><span class="line">        !((InetSocketAddress) localAddress).getAddress().isAnyLocalAddress() &amp;&amp;</span><br><span class="line">        !PlatformDependent.isWindows() &amp;&amp; !PlatformDependent.isRoot()) &#123;</span><br><span class="line">        <span class="comment">// Warn a user about the fact that a non-root user can&#x27;t receive a</span></span><br><span class="line">        <span class="comment">// broadcast packet on *nix if the socket is bound on non-wildcard address.</span></span><br><span class="line">        logger.warn(</span><br><span class="line">            <span class="string">&quot;A non-root user can&#x27;t receive a broadcast packet if the socket &quot;</span> +</span><br><span class="line">            <span class="string">&quot;is not bound to a wildcard address; binding to a non-wildcard &quot;</span> +</span><br><span class="line">            <span class="string">&quot;address (&quot;</span> + localAddress + <span class="string">&quot;) anyway as requested.&quot;</span>);</span><br><span class="line">    &#125;</span><br><span class="line">	<span class="comment">//在调用doBind方法前获取isActive。</span></span><br><span class="line">    <span class="keyword">boolean</span> wasActive = isActive();</span><br><span class="line">    <span class="keyword">try</span> &#123;</span><br><span class="line">        doBind(localAddress);</span><br><span class="line">    &#125; <span class="keyword">catch</span> (Throwable t) &#123;</span><br><span class="line">        safeSetFailure(promise, t);</span><br><span class="line">        closeIfClosed();</span><br><span class="line">        <span class="keyword">return</span>;</span><br><span class="line">    &#125;</span><br><span class="line">	<span class="comment">//当只有执行`doBind();`方法前isActive是false,执行之后是true,才会去进行通知，触发用户代码中handler的`channelActive(ctx);`。</span></span><br><span class="line">    <span class="keyword">if</span> (!wasActive &amp;&amp; isActive()) &#123;</span><br><span class="line">        invokeLater(<span class="keyword">new</span> Runnable() &#123;</span><br><span class="line">            <span class="meta">@Override</span></span><br><span class="line">            <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">run</span><span class="params">()</span> </span>&#123;</span><br><span class="line">                pipeline.fireChannelActive();</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    safeSetSuccess(promise);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>然后调用<code>doBind();</code>方法，这个方法是一个抽象方法，实现是在他的子类中，所以，最终绑定发生在<code>NioServerSocketChannel</code>类的<code>bind();</code>方法。这里比较绕，建议多看几次。最后绑定端口，代码很简单，就是通过jdk底层的channel进行端口的绑定。代码如下：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line">NioServerSocketChannel.java</span><br><span class="line"><span class="meta">@Override</span></span><br><span class="line"><span class="function"><span class="keyword">protected</span> <span class="keyword">void</span> <span class="title">doBind</span><span class="params">(SocketAddress localAddress)</span> <span class="keyword">throws</span> Exception </span>&#123;</span><br><span class="line">    <span class="keyword">if</span> (PlatformDependent.javaVersion() &gt;= <span class="number">7</span>) &#123;</span><br><span class="line">        javaChannel().bind(localAddress, config.getBacklog());</span><br><span class="line">    &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">        javaChannel().socket().bind(localAddress, config.getBacklog());</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>其中这个事件传播是从pipeline进行传播，我们来看看这个pipeline做了哪些事情。我们跟进去发现，他触发了pipeline中的一个head的<code>invokeChannelActive();</code>方法。而这个方法最终调用的就是DefaultChannelPipeline的HeadContext子类的<code>channelActive(ctx);</code>方法，代码如下：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@Override</span></span><br><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">channelActive</span><span class="params">(ChannelHandlerContext ctx)</span> <span class="keyword">throws</span> Exception </span>&#123;</span><br><span class="line">    ctx.fireChannelActive();</span><br><span class="line"></span><br><span class="line">    readIfIsAutoRead();</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>通过这个<code>ctx.fireChannelActive();</code>方法调用用户代码中的自定义handler的<code>channelActive(ctx);</code>方法，然后调用了一个<code>readIfIsAutoRead();</code>这个方法会触发<code>channel.read();</code>事件。最终会从pipeline开始传播，我们来看看到底这个read，做了什么事情。他传播到了pipeline的一个tail的一个read方法。这个tail是pipeline中的一个默认的节点，它是最尾部的一个节点。事件传播后续文章会继续详细讲解，最终会调用到<code>AbstractChannel.AbstractUnSafe</code>类的<code>beginRead();</code> 然后调用一个<code>doBeginRead();</code>方法。我们进去看看这个方法做了什么事情。最终在<code>AbstractNioChannel</code>中的<code>doBeginRead();</code>方法。代码如下：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@Override</span></span><br><span class="line"><span class="function"><span class="keyword">protected</span> <span class="keyword">void</span> <span class="title">doBeginRead</span><span class="params">()</span> <span class="keyword">throws</span> Exception </span>&#123;</span><br><span class="line">    <span class="comment">// Channel.read() or ChannelHandlerContext.read() was called</span></span><br><span class="line">    <span class="keyword">final</span> SelectionKey selectionKey = <span class="keyword">this</span>.selectionKey;</span><br><span class="line">    <span class="keyword">if</span> (!selectionKey.isValid()) &#123;</span><br><span class="line">        <span class="keyword">return</span>;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    readPending = <span class="keyword">true</span>;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">final</span> <span class="keyword">int</span> interestOps = selectionKey.interestOps();</span><br><span class="line">    <span class="keyword">if</span> ((interestOps &amp; readInterestOp) == <span class="number">0</span>) &#123;</span><br><span class="line">        selectionKey.interestOps(interestOps | readInterestOp);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>看到这里，如果对jdk nio熟悉的同学，应该就比较明白了。首先我们先拿到selectionKey，这个就是我们之前代码中讲到注册服务端channel到selector上去的时候返回的一个selectionKey。然后拿到这个selectionKey的一个事件。还还记得我们填写的事件是啥吗？是一个0，忘记的可以看看前面的代码。那么interestOps的结果是0。那么这个条件成立。<code>selectionKey.interestOps(interestOps | readInterestOp);</code>其实就是一个新的readInterestOp事件重新添加到selectionKey中的呢？那么这个readInterestOp到底代表的是什么事件呢？如果你还有印象，那么就会知道，这个readInterestOp其实就是一个accept事件。（在NioServerSocketChannel的构造函数时，调用父类构造函数，传入的就是一个SelectionKey.OP_ACCEPT）。</p>
<h2 id="总结"><a href="#总结" class="headerlink" title="总结"></a>总结</h2><p>通过上述步骤，我们一步步对源码进行分析，我们知道了这个netty服务端是怎么启动的。如果你还对netty服务端的启动不是很清楚，建议结合本篇文章，自己去多看看netty的源码，好好的梳理一下~</p>
<p><img src="https://gitee.com/zeroable/ima/raw/master/img/EWM_GZH_MNXT.png"></p>

    </div>

    
    
    

      <footer class="post-footer">
          <div class="post-tags">
              <a href="/tags/netty/" rel="tag"># netty</a>
              <a href="/tags/java/" rel="tag"># java</a>
          </div>

        


        
    <div class="post-nav">
      <div class="post-nav-item">
    <a href="/2021/10/08/netty%E6%BA%90%E7%A0%81%E8%A7%A3%E6%9E%9001-NioEventLoop%E8%AF%A6%E8%A7%A3/" rel="prev" title="netty源码解析01-NioEventLoop详解">
      <i class="fa fa-chevron-left"></i> netty源码解析01-NioEventLoop详解
    </a></div>
      <div class="post-nav-item">
    <a href="/2021/11/10/netty%E6%BA%90%E7%A0%81%E8%A7%A3%E6%9E%9002-%E6%96%B0%E8%BF%9E%E6%8E%A5%E7%9A%84%E5%A4%84%E7%90%86/" rel="next" title="netty源码解析02-新连接的处理以及添加读事件的添加">
      netty源码解析02-新连接的处理以及添加读事件的添加 <i class="fa fa-chevron-right"></i>
    </a></div>
    </div>
      </footer>
    
  </article>
  
  
  



          </div>
          
    
  <div class="comments">
    <div id="lv-container" data-id="city" data-uid="MTAyMC81NDY0NS8zMTExNg=="></div>
  </div>
  

<script>
  window.addEventListener('tabs:register', () => {
    let { activeClass } = CONFIG.comments;
    if (CONFIG.comments.storage) {
      activeClass = localStorage.getItem('comments_active') || activeClass;
    }
    if (activeClass) {
      let activeTab = document.querySelector(`a[href="#comment-${activeClass}"]`);
      if (activeTab) {
        activeTab.click();
      }
    }
  });
  if (CONFIG.comments.storage) {
    window.addEventListener('tabs:click', event => {
      if (!event.target.matches('.tabs-comment .tab-content .tab-pane')) return;
      let commentClass = event.target.classList[1];
      localStorage.setItem('comments_active', commentClass);
    });
  }
</script>

        </div>
          
  
  <div class="toggle sidebar-toggle">
    <span class="toggle-line toggle-line-first"></span>
    <span class="toggle-line toggle-line-middle"></span>
    <span class="toggle-line toggle-line-last"></span>
  </div>

  <aside class="sidebar">
    <div class="sidebar-inner">

      <ul class="sidebar-nav motion-element">
        <li class="sidebar-nav-toc">
          文章目录
        </li>
        <li class="sidebar-nav-overview">
          站点概览
        </li>
      </ul>

      <!--noindex-->
      <div class="post-toc-wrap sidebar-panel">
          <div class="post-toc motion-element"><ol class="nav"><li class="nav-item nav-level-1"><a class="nav-link" href="#netty-%E6%9C%8D%E5%8A%A1%E7%AB%AF%E5%90%AF%E5%8A%A8"><span class="nav-number">1.</span> <span class="nav-text">netty 服务端启动</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#%E5%88%9B%E5%BB%BA%E6%9C%8D%E5%8A%A1%E7%AB%AFChannel"><span class="nav-number">1.1.</span> <span class="nav-text">创建服务端Channel</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#%E7%94%A8%E6%88%B7%E4%BB%A3%E7%A0%81%E5%85%A5%E5%8F%A3"><span class="nav-number">1.1.1.</span> <span class="nav-text">用户代码入口</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#%E5%88%9D%E5%A7%8B%E5%8C%96%E5%B9%B6%E6%B3%A8%E5%86%8C"><span class="nav-number">1.1.2.</span> <span class="nav-text">初始化并注册</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#%E5%88%9B%E5%BB%BAjava%E6%9C%8D%E5%8A%A1%E7%AB%AFChannel"><span class="nav-number">1.1.3.</span> <span class="nav-text">创建java服务端Channel</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#%E5%88%9B%E5%BB%BA%E5%BA%95%E5%B1%82jdk-channel"><span class="nav-number">1.1.3.1.</span> <span class="nav-text">创建底层jdk channel</span></a></li></ol></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#%E5%88%9D%E5%A7%8B%E5%8C%96Channel"><span class="nav-number">1.2.</span> <span class="nav-text">初始化Channel</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#%E6%B3%A8%E5%86%8CSelector"><span class="nav-number">1.3.</span> <span class="nav-text">注册Selector</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#%E7%BB%91%E5%AE%9A%E7%AB%AF%E5%8F%A3"><span class="nav-number">1.4.</span> <span class="nav-text">绑定端口</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#%E6%80%BB%E7%BB%93"><span class="nav-number">1.5.</span> <span class="nav-text">总结</span></a></li></ol></li></ol></div>
      </div>
      <!--/noindex-->

      <div class="site-overview-wrap sidebar-panel">
        <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
  <p class="site-author-name" itemprop="name">zeroable</p>
  <div class="site-description" itemprop="description">种一棵树最好的时间是十年前，其次是现在。</div>
</div>
<div class="site-state-wrap motion-element">
  <nav class="site-state">
      <div class="site-state-item site-state-posts">
          <a href="/archives/">
        
          <span class="site-state-item-count">4</span>
          <span class="site-state-item-name">日志</span>
        </a>
      </div>
      <div class="site-state-item site-state-categories">
            <a href="/categories/">
          
        <span class="site-state-item-count">2</span>
        <span class="site-state-item-name">分类</span></a>
      </div>
      <div class="site-state-item site-state-tags">
            <a href="/tags/">
          
        <span class="site-state-item-count">2</span>
        <span class="site-state-item-name">标签</span></a>
      </div>
  </nav>
</div>
  <div class="links-of-author motion-element">
      <span class="links-of-author-item">
        <a href="mailto:2011277648@qq.com" title="E-Mail → mailto:2011277648@qq.com" rel="noopener" target="_blank"><i class="fa fa-envelope fa-fw"></i>E-Mail</a>
      </span>
      <span class="links-of-author-item">
        <a href="https://gitee.com/zeroable/ima/raw/master/img/EWM_GZH_MNXT.png" title="微信公众号 → https:&#x2F;&#x2F;gitee.com&#x2F;zeroable&#x2F;ima&#x2F;raw&#x2F;master&#x2F;img&#x2F;EWM_GZH_MNXT.png" rel="noopener" target="_blank"><i class="fab fa-weixin fa-fw"></i>微信公众号</a>
      </span>
      <span class="links-of-author-item">
        <a href="https://www.zhihu.com/people/zeroable" title="知乎 → https:&#x2F;&#x2F;www.zhihu.com&#x2F;people&#x2F;zeroable" rel="noopener" target="_blank"><i class="fab fa-zhihu fa-fw"></i>知乎</a>
      </span>
      <span class="links-of-author-item">
        <a href="https://blog.csdn.net/qq_36707152" title="csdn → https:&#x2F;&#x2F;blog.csdn.net&#x2F;qq_36707152" rel="noopener" target="_blank"><i class="fab fa-csdn fa-fw"></i>csdn</a>
      </span>
  </div>



      </div>
      <div class="wechat_OA">
        <span>欢迎关注我的公众号</span>
        <br>
          <!-- 这里添加你的二维码图片 -->
        <img src ="https://gitee.com/zeroable/ima/raw/master/img/微信公众号.jpg">
      </div

    </div>
  </aside>
  <div id="sidebar-dimmer"></div>


      </div>
    </main>

    <footer class="footer">
      <div class="footer-inner">
        

        

<div class="copyright">
  
  &copy; 
  <span itemprop="copyrightYear">2021</span>
  <span class="with-love">
    <i class="fa fa-heart"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">zeroable</span>
</div>

        
<div class="busuanzi-count">
  <script async src="https://busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script>
    <span class="post-meta-item" id="busuanzi_container_site_uv" style="display: none;">
      <span class="post-meta-item-icon">
        <i class="fa fa-user"></i>
      </span>
      <span class="site-uv" title="总访客量">
        <span id="busuanzi_value_site_uv"></span>
      </span>
    </span>
    <span class="post-meta-divider">|</span>
    <span class="post-meta-item" id="busuanzi_container_site_pv" style="display: none;">
      <span class="post-meta-item-icon">
        <i class="fa fa-eye"></i>
      </span>
      <span class="site-pv" title="总访问量">
        <span id="busuanzi_value_site_pv"></span>
      </span>
    </span>
</div>








      </div>
    </footer>
  </div>

  
  <script src="/lib/anime.min.js"></script>
  <script src="/lib/velocity/velocity.min.js"></script>
  <script src="/lib/velocity/velocity.ui.min.js"></script>

<script src="/js/utils.js"></script>

<script src="/js/motion.js"></script>


<script src="/js/schemes/pisces.js"></script>


<script src="/js/next-boot.js"></script>




  















  

  

<script>
NexT.utils.loadComments(document.querySelector('#lv-container'), () => {
  window.livereOptions = {
    refer: location.pathname.replace(CONFIG.root, '').replace('index.html', '')
  };
  (function(d, s) {
    var j, e = d.getElementsByTagName(s)[0];
    if (typeof LivereTower === 'function') { return; }
    j = d.createElement(s);
    j.src = 'https://cdn-city.livere.com/js/embed.dist.js';
    j.async = true;
    e.parentNode.insertBefore(j, e);
  })(document, 'script');
});
</script>

</body>
</html>
